<template>
  <div style="float:left;margin-left:10px;">
    <template v-if="picture_3">
      <div class="img-upload" style="display:inline-block;">
        <el-upload
          :action="qiniuUploadUrl"
          :on-preview="handlePictureCardPreview_1"
          list-type="picture-card"
          :before-upload="beforeUpload"
          :on-remove="handleRemove_1"
          :class="{hide:picture_1}"
          :on-change="first_picture"
          :on-success="handleSuccess"
          :data="qiniuData"
        >
          <div class="el-icon-plus avatar-uploader-icon">
            <i />
            <div style="min-width:80px;">{{ tip }}</div>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt>
        </el-dialog>
      </div>
    </template>
    <template v-else>
      <div :class="{'img-upload':true,hide:picture_2}" style="display:inline-block;">
        <el-upload
          :action="qiniuUploadUrl"
          :on-preview="handlePictureCardPreview_1"
          list-type="picture-card"
          :before-upload="beforeUpload"
          :before-remove="handleRemove_1"
          :class="{hide:picture_1}"
          :on-change="first_picture"
          :on-success="handleSuccess"
          :data="qiniuData"
          :file-list="pictureDetail"
        >
          <div class="el-icon-plus avatar-uploader-icon">
            <i />
            <div style="min-width:80px;">{{ tip }}</div>
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt>
        </el-dialog>
      </div>
    </template>
  </div>
</template>
<script>
const pinyin = require('chinese-to-pinyin');
import { testPicType, testPicSize } from '@/utils/img';
import { getToken, deleteQnImg } from '@/api/qiniu';
import { mapGetters } from 'vuex';
export default {
  name: 'ImageUpload',
  props: {
    tip: {
      type: String,
      default: '添加上传图片'
    },
    size: {
      type: Number,
      required: true
    },
    imgname: {
      type: String,
      default: '图片'
    },
    position: {
      type: Number,
      required: true
    },
    picturereturn: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      qiniuData: {
        token: '',
        key: ''
      },
      url: '',
      id: 'pic1',
      dialogVisible: false,
      picture_1: false,
      picture_2: true, // 回显图片
      picture_3: true, // 添加无图片
      limitCount: 1,
      dialogImageUrl: '',
      // 传递过来的图片
      pictureDetail: [{ url: null }],
      testReturn: false
    };
  },
  computed: {
    ...mapGetters(['qiniuUploadUrl', 'qiniuResUrl'])
  },
  watch: {
    picturereturn() {
      if (this.picturereturn[this.position - 1].url) {
        this.pictureDetail[0].url = this.qnPath(this.picturereturn[this.position - 1].url);
        this.testReturn = true;
        this.picture_3 = false;
      } else {
        this.testReturn = false;
        this.picture_3 = true;
      }
    }
  },
  created() {
    const id = sessionStorage.getItem('handleEdit');
    if (id && id.length > 1) {
      this.picture_1 = false;
    }
  },
  methods: {
    async beforeUpload(file) {
      if (!testPicType(file) || !testPicSize(file, this.size, this.imgName)) {
        return;
      }
      const res = await getToken();
      this.qiniuData.token = res.data;
      this.qiniuData.key = `${file.uid}-${pinyin(file.name, {
        keepRest: true,
        firstCharacter: true,
        removeSpace: true
      })}`;
    },
    handleSuccess(res, file) {
      this.$emit('onSuccess', {
        url: `${res.key}`,
        position: this.position
      });
    },
    // 图片删除
    handleRemove_1(file, fileList) {
      const param = {
        path: this.picturereturn[this.position - 1].url
      };
      new Promise((resolve, reject) => {
        deleteQnImg(param).then(res => {
          if (res.code === '0000') {
            this.picture_1 = fileList.length >= this.limitCount;
            this.picture_2 = fileList.length >= this.limitCount;
            if (this.testReturn) {
              this.$emit('deletePicUrl', { position: this.position, code: '0000' });
            } else {
              this.$emit('deletePicUrl', { position: this.position, code: '-1' });
            }
            resolve(res);
          } else {
            reject(res);
          }
        }).catch(error => {
          this.$emit('deletePicUrl', { position: this.position, code: '-1' });
          this.picture_1 = fileList.length >= this.limitCount;
          this.picture_2 = fileList.length >= this.limitCount;
          reject(error);
        });
      });
    },
    handlePictureCardPreview_1(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    first_picture(file, fileList) {
      this.picture_1 = fileList.length >= this.limitCount;
      this.picture_2 = fileList.length >= this.limitCount;
    }
  }
};
</script>
<style lang="scss" scoped>
.img-upload {
  & > div {
    display: inline-block;
  }
  /deep/.el-upload {
    width: 120px!important;
    height: 120px!important;
    box-sizing: content-box;
    padding: 2px;
  }
  /deep/.el-upload-list__item {
    width: 120px;
    height: 120px;
  }
  .avatar-uploader {
    display: inline-block !important;
    padding-right: 20px;
  }
  /deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .el-icon-plus:before {
    color: #1182fb;
    width: 22px;
    height: 22px;
    font-weight: 600;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
  .el-icon-plus {
    width: 118px;
    height: 118px;
    background: rgba(255, 255, 255, 1);
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
    align-items: center;
    & > div {
      width: 73px;
      height: 20px;
      font-size: 12px;
      font-weight: 400;
      color: rgba(131, 138, 157, 1);
      line-height: 20px;
    }
  }
}
.hide .el-upload--picture-card {
  display: none;
}
</style>
